﻿
using System.Collections.Generic;
using System.Text;

namespace System
{
    public static class HexHelper
    {
        /// <summary>
        /// 将十六进制字符串转换为字节数组
        /// </summary>
        /// <param name="hex"></param>
        /// <param name="autoPaddingLeft">当字符数量为奇数时，是否在左侧补一个0</param>
        /// <returns></returns>
        public static byte[] HexToBytes(string hex, bool autoPaddingLeft = false)
        {
            hex = hex.Trim();
            if (hex.Contains(" "))
            {
                var hexs = hex.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                byte[] data = new byte[hexs.Length];
                for (int i = 0; i < hexs.Length; i++)
                {
                    data[i] = Convert.ToByte(hexs[i], 16);
                }
                return data;
            }
            else
            {
                if (hex.Length % 2 != 0)
                {
                    if (autoPaddingLeft)
                    {
                        hex = "0" + hex;
                    }
                    else
                    {
                        throw new Exception("十六进制字符串字符数必须为2的倍数。");
                    }
                }
                var count = hex.Length / 2;
                byte[] data = new byte[count];
                for (int i = 0; i < count; i++)
                {
                    data[i] = Convert.ToByte(hex.Substring(i * 2, 2), 16);
                }
                return data;
            }
        }
        /// <summary>
        /// 将字节数组转换为16进制字符串
        /// </summary>
        /// <param name="data"></param>
        /// <param name="splitor">分隔符</param>
        /// <returns></returns>
        public static string BytesToHexString(byte[] data, string splitor = "")
        {
            string[] strs = new string[data.Length];
            for (int i = 0; i < data.Length; i++)
            {
                strs[i] = data[i].ToString("X2");
            }
            return string.Join(splitor, strs);
        }
    }
}
